<template>
  <div class="admin-management">
    <div class="page-header">
      <h2>管理员管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="管理员编号">
          <el-input v-model="searchForm.adminNo" placeholder="请输入管理员编号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.adminName" placeholder="请输入姓名" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.adminRole" placeholder="请选择角色" clearable style="width: 160px">
            <el-option label="管理员" value="admin" />
            <el-option label="超级管理员" value="super_admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.adminStatus" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="handleReset"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增管理员</el-button>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="adminList" 
        v-loading="loading" 
        stripe 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="adminNo" label="编号" width="140" />
        <el-table-column prop="adminName" label="姓名" width="140" />
        <el-table-column prop="adminRole" label="角色" width="120">
          <template #default="scope">{{ roleText(scope.row.adminRole) }}</template>
        </el-table-column>
        <el-table-column prop="adminStatus" label="状态" width="100">
          <template #default="scope">{{ statusText(scope.row.adminStatus) }}</template>
        </el-table-column>
        <el-table-column prop="adminPhone" label="手机号" width="150" />
        <el-table-column prop="adminEmail" label="邮箱" width="200" />
        <el-table-column prop="updateTime" label="更新时间" width="170">
          <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10,20,50,100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="640px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="管理员编号" prop="adminNo">
          <el-input v-model="form.adminNo" placeholder="请输入管理员编号" />
        </el-form-item>
        <el-form-item label="姓名" prop="adminName">
          <el-input v-model="form.adminName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="adminRole">
          <el-select v-model="form.adminRole" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="超级管理员" value="super_admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="adminStatus">
          <el-select v-model="form.adminStatus" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="adminPhone">
          <el-input v-model="form.adminPhone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="adminEmail">
          <el-input v-model="form.adminEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="备注" prop="adminRemark">
          <el-input v-model="form.adminRemark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="adminPassword">
          <el-input v-model="form.adminPassword" placeholder="请输入初始密码" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="管理员详情" width="600px">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="编号">{{ detailData.adminNo }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ detailData.adminName }}</el-descriptions-item>
          <el-descriptions-item label="角色">{{ roleText(detailData.adminRole) }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ statusText(detailData.adminStatus) }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ detailData.adminPhone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ detailData.adminEmail }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ formatDate(detailData.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.adminRemark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { getAdminList, getAdminDetail, addAdmin, updateAdmin, deleteAdmin, deleteAdmins } from '../api/admin'

const searchForm = reactive({
  adminNo: '',
  adminName: '',
  adminRole: '',
  adminStatus: ''
})

const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 })
const adminList = ref([])
const loading = ref(false)
const selectedIds = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

const detailDialogVisible = ref(false)
const detailData = ref({})

const form = reactive({
  adminId: null,
  adminNo: '',
  adminName: '',
  adminRole: 'admin',
  adminStatus: 1,
  adminPhone: '',
  adminEmail: '',
  adminRemark: '',
  adminPassword: ''
})

const rules = {
  adminNo: [{ required: true, message: '请输入管理员编号', trigger: 'blur' }],
  adminName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  adminRole: [{ required: true, message: '请选择角色', trigger: 'change' }],
  adminStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
  adminPhone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  adminEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  adminPassword: [
    { required: (form) => !isEdit.value, message: '请输入初始密码', trigger: 'blur' }
  ]
}

const formRef = ref()

const roleText = (role) => {
  if (role === 'super_admin') return '超级管理员'
  return '管理员'
}

const statusText = (status) => {
  if (status === 1) return '启用'
  if (status === 0) return '禁用'
  return status ?? '-'
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchAdminList()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(k => searchForm[k] = '')
  pagination.currentPage = 1
  fetchAdminList()
}

const handleAdd = () => {
  dialogTitle.value = '新增管理员'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleViewDetail = async (row) => {
  try {
    const response = await getAdminDetail(parseInt(row.adminId))
    detailData.value = response.data || { ...row }
  } catch (e) {
    detailData.value = { ...row }
  }
  detailDialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑管理员'
  isEdit.value = true
  Object.keys(form).forEach(k => form[k] = row[k] ?? (k === 'adminStatus' ? 1 : ''))
  form.adminPassword = ''
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除管理员 "${row.adminName}" 吗？`, '删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      await deleteAdmin(parseInt(row.adminId))
      ElMessage.success('删除成功')
      fetchAdminList()
    })
    .catch(() => ElMessage.info('已取消删除'))
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.adminId)
}

const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的管理员')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个管理员吗？`, '批量删除确认', { 
    confirmButtonText: '确定', 
    cancelButtonText: '取消', 
    type: 'warning' 
  })
    .then(async () => {
      await deleteAdmins(selectedIds.value)
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      fetchAdminList()
    })
    .catch(() => ElMessage.info('已取消删除'))
}

const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    if (isEdit.value) {
      // 后端可能使用下划线命名，这里做一次转换
      const { adminPassword, ...updateData } = form
      await updateAdmin(updateData)
      ElMessage.success('编辑成功')
    } else {
      const { adminId, ...addData } = form
      await addAdmin(addData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    fetchAdminList()
  } catch (e) {
    // 已由拦截器提示
  }
}

const handleDialogClose = () => {
  resetForm()
  formRef.value?.resetFields()
}

const resetForm = () => {
  Object.keys(form).forEach(k => {
    if (k === 'adminId') form[k] = null
    else if (k === 'adminStatus') form[k] = 1
    else if (k === 'adminRole') form[k] = 'admin'
    else form[k] = ''
  })
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchAdminList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchAdminList()
}

const toCamel = (obj) => {
  if (!obj || typeof obj !== 'object') return obj
  const mapKey = (k) => k.replace(/_([a-z])/g, (_, c) => c.toUpperCase())
  const result = {}
  Object.keys(obj).forEach(k => { result[mapKey(k)] = obj[k] })
  return result
}

const fetchAdminList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      adminNo: searchForm.adminNo || '',
      adminName: searchForm.adminName || '',
      adminRole: searchForm.adminRole || '',
      adminStatus: searchForm.adminStatus || ''
    }
    const response = await getAdminList(params)
    if (response.data) {
      const raw = response.data.records || response.data.list || []
      adminList.value = raw.map(toCamel)
      pagination.total = response.data.total || 0
    } else {
      adminList.value = []
      pagination.total = 0
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => fetchAdminList())
</script>

<style scoped>
.admin-management { background: #f5f7fa; padding: 20px; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif; box-sizing: border-box; }
.page-header { margin-bottom: 32px; text-align: center; }
.page-header h2 { margin: 0; color: #2c3e50; font-size: 28px; font-weight: 600; letter-spacing: 1px; }
.search-card { margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; }
.search-card :deep(.el-card__body) { padding: 20px; }
.search-form :deep(.el-form-item) { margin-bottom: 16px; margin-right: 24px; }
.action-card { margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; }
.action-card :deep(.el-card__body) { padding: 16px 20px; }
.action-buttons { display: flex; justify-content: flex-start; }
.table-card { border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; overflow: hidden; }
.table-card :deep(.el-card__body) { padding: 0; }
.pagination-container { margin-top: 16px; padding: 16px 20px; display: flex; justify-content: center; background: #f5f7fa; border-top: 1px solid #ebeef5; }
.dialog-footer { display: flex; justify-content: flex-end; gap: 12px; padding-top: 16px; }

/* 详情对话框样式 */
.detail-content { padding: 20px 0; }
.detail-content :deep(.el-descriptions__header) { background: #f5f7fa; padding: 16px 20px; border-bottom: 1px solid #ebeef5; }
</style>